<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxCircleRepositores;
use App\Http\Requests\Api\PostsRequests\CircleRequest;
use App\Jobs\Icon\UpdateIconImgWHJob;
use App\Jobs\System\CheckBatchCahceDataLossJob;
use App\Jobs\TopicImgJob;
use App\Jobs\UserInputSafeCheckJob;
use App\Lib\Classes\AcAutomation;
use App\Lib\WeApp\WeApp;
use App\Models\Circle\WxCircle;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxTag;
use App\Models\User\WxUserStudentCertify;
use App\Models\WxActivity;
use App\Models\WxCaptchaImg;
use App\Models\WxIcon;
use App\Models\WxPageEvent;
use App\Models\WxQuestion;
use App\Models\WxTenant;
use App\Models\WxUniversity;
use App\Wen\Utils\AdminUtils;
use App\Wen\Utils\BaiduUtils;
use App\Wen\Utils\CircleUtils;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\ImageUtils;
use App\Wen\Utils\PostUtils;
use App\Wen\Utils\RealtimeUtils;
use App\Wen\Utils\SearchUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\ShopUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use App\Http\Controllers\Api\Repositories\WxSearchRepositores;
use App\Models\WxClause;
use App\Models\WxSearch;
use App\Models\WxSlideshow;
use App\Models\User\WxUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Laravel\Socialite\Facades\Socialite;

class CommonController extends BaseController
{
    /** 把日志写到公共日志
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function putLog(Request $request){
        $log = $request->log;
        _logger_(__file__, __line__, $log);
        return $this->success();
    }

    public function tenants(Request $request){
        $latitude = $request->latitude;
        $longitude = $request->longitude;
        $keyword = _empty_default_($request->keyword, '');
        $uid = $request->uid;
        if(_empty_($latitude) && _empty_($longitude)){
            if($uid > 0){
                $user = UserUtils::get_cached_user($uid);
                if($user && _abs(_array_key($user, 'latitude', 0)) > 0 && _abs(_array_key($user, 'longitude', 0)) > 0){
                    $latitude = $user['latitude'];
                    $longitude = $user['longitude'];
                }else{
//                    return $this->fail(200001);
                }
            }else{
//                return $this->fail(200001);
            }
        }

        try {
            $is_multi_site = Settings::get('is_multi_site', 0);
            $query = WxTenant::where('status', 0);
            if($is_multi_site == 1){
                $query = $query->where('tenant_id', '!=', 999);
            }else if($is_multi_site == 2){

            }else if($is_multi_site == 3){
                $query = $query->where('tenant_id', '!=', 0)->where('tenant_id', '!=', 999);
            }else{
                $query = $query->where('tenant_id', 0);
            }

            if($keyword){
                $query = $query->where(function ($query) use ($keyword) {
                    if(is_numeric($keyword)){
                        $query->orWhere('name', 'like', '%' . $keyword . '%')
                            ->orWhere('short', 'like', '%' . $keyword . '%')
                            ->orWhere('tenant_id', $keyword);
                    }else{
                        $query->orWhere('name', 'like', '%' . $keyword . '%')
                            ->orWhere('short', 'like', '%' . $keyword . '%');
                    }
                });
            }

            if(_abs($latitude) > 0 && _abs($longitude) > 0){
                $tenants = $query->select(DB::raw('*, ( 6371 * acos( cos( radians('.$latitude.') ) * cos( radians( add_latitude ) ) * cos( radians( add_longitude ) - radians('.$longitude.') ) + sin( radians('.$latitude.') ) * sin( radians( add_latitude ) ) ) ) AS distance'))
                    ->orderBy('distance')->orderBy('order', 'desc')->orderBy('tenant_id', 'desc')->get();
                if($uid > 0){
                    WxUser::where('id', $uid)->update(['longitude'=>$longitude, 'latitude'=>$latitude]);
                    Cache::forget('get:cached:user:'.$uid);
                }
            }else{
                $tenants = $query->orderBy('order', 'desc')->orderBy('tenant_id', 'desc')->get();
            }

            if($tenants){
                $tenants->map(function ($v){
                    global $__MINI_GLOBAL_TENANTS_ARR__;
                    if(in_array($v->tenant_id, $__MINI_GLOBAL_TENANTS_ARR__)){
                        $v->auth = true;
                    }else{
                        $v->auth = false;
                    }
                    if($v->distance && $v->distance > 0){
                        $v->distance = (int)(1000 * $v->distance);
                        if($v->distance < 10){
                            $v->distance = '<10m';
                        }else if($v->distance >= 1000 && $v->distance <= 200000){
                            $v->distance = '<'. round($v->distance / 1000, 2).'km';
                        }else if($v->distance > 200000){
                            $v->distance = round($v->distance / 1000, 2).'km';
                        }else{
                            $v->distance = '<'.(int)$v->distance.'m';
                        }
                    }else{
                        $v->distance = '';
                    }
                    return $v;
                });
            }
            return $this->success($tenants);
        }catch (\Exception $e){
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200006);
        }
    }

    public function download(Request $request){
        $path = $request->path;
        if(file_exists(public_path('storage/'.$path))){
            return response()->download(public_path('storage/'.$path));
        }else{
            return $this->fail(200003);
        }
    }

    public function clause(Request $request){
        $id = $request->id;

        if(_empty_($id)){
            return $this->fail(200001);
        }

        $clause = WxClause::find($id);
        if($clause){
            return view('common/default', ['title' => $clause->title, 'body'=>$clause->content]);
        }
        return $this->fail(200003);
    }

    public function express_range(){
        return $this->success(ShopUtils::get_expree_name_range());
    }


    /**
     * 搜索
     * @param Request $request
     * type 0:笔记；1：圈子；2：用户 3:商品
     */
    public function search(Request $request)
    {
        $keyword = $request->keyword;
        $type = $request->type;
        $uid = $request->uid;
        $is_tenant = _empty_default_($request->isTenant, false);
        if(_empty_($is_tenant)){
            $is_tenant = false;
        }else{
            $is_tenant = true;
        }
        if(_empty_($uid)){
            $uid = 0;
        }

        if(_empty_($type, true)){
            return $this->fail(200001);
        }
        if(_empty_($keyword)){
            if($type == 1 || $type == 3){

            }else{
                return $this->fail(200001);
            }
        }
        _limit_user('search', $uid, 40);

        $limit = $request->input('limit', 10);
        $keyword_actree = (SearchUtils::is_use_es() && $keyword) ? new AcAutomation(SearchUtils::split_keywords($keyword)) : null;
        if ($type == 0) {
            $data = SearchUtils::search_post($keyword_actree, $keyword, $uid, $limit, $is_tenant);
        } else if ($type == 1) {
            if($keyword){
                $data = SearchUtils::search_cicle($keyword_actree, $keyword, $uid, $limit, $is_tenant);
            }else{
                $follow = _empty_default_($request->follow, 0);
                if($follow == -1){
                    $app_find_tab = Settings::get('app_find_tab', []);
                    if(_empty_($app_find_tab) || _empty_($app_find_tab[0])){
                        return $this->fail(200004, [], '请先去后台[移动端-发现-圈子发现页-tab]进行配置');
                    }
                    $follow = $app_find_tab[0]['follow_status'];
                    $orderBy = $app_find_tab[0]['orderBy'];
                    $order = $app_find_tab[0]['order'];
                    $tags = $app_find_tab[0]['tags'];
                    if(_empty_($orderBy)){
                        $orderBy = 'created_at';
                    }
                    $master = $app_find_tab[0]['master'] ?? 0;
                }else{
                    if(!in_array($follow, [0, 1, 2])){
                        return $this->fail(200004);
                    }
                    $orderBy = _empty_default_($request->orderBy, 'created_at');
                    if(!in_array($orderBy, ['created_at', 'last_publish_at', 'last_enter_at', 'total_post_count', 'total_comment_count', 'follow_at', 'count_circle_follow', 'count_pay_content'])){
                        return $this->fail(200004);
                    }
                    $order = _empty_default_($request->order, 'desc');
                    if(!in_array($order, ['desc', 'asc'])){
                        return $this->fail(200004);
                    }
                    $tags = _empty_default_($request->tags, '');
                    $master = _empty_default_($request->master, 0);
                }
                if(is_string($tags)){
                    $tags = explode(',', $tags);
                }
                if($master == 1){
                    $master = 1;
                }else{
                    $master = 0;
                }
                $tags_ = [];
                if(is_array($tags) && $tags){
                    foreach ($tags as $tag){
                        $tag = (int)$tag;
                        if($tag > 0){
                            $tags_[] = $tag;
                        }
                    }
                }

                $data = CircleUtils::circle_filter($is_tenant, $follow, $tags, $orderBy, $order, $master);
            }
        } else if($type == 2){
            $data = SearchUtils::search_user($keyword_actree, $keyword, $uid, true, $limit, $is_tenant);
        } else if($type == 3){
            if($keyword){
                $data = SearchUtils::search_goods($keyword_actree, $keyword, $uid, $limit);
            }else{
                $follow = _empty_default_($request->follow, 0);
                if($follow == -1){
                    $app_find_tab = Settings::get('app_find2_tab', []);
                    if(_empty_($app_find_tab) || _empty_($app_find_tab[0])){
                        return $this->fail(200004, [], '请先去后台[移动端-商品发现页-tab]进行配置');
                    }
                    $follow = $app_find_tab[0]['follow_status'];
                    $orderBy = $app_find_tab[0]['orderBy'];
                    $order = $app_find_tab[0]['order'];
                    $ids = $app_find_tab[0]['ids'];
                    $types = $app_find_tab[0]['types'];
                    if(is_string($types)){
                        $types = json_decode($types, true);
                    }
                    if(_empty_(end($types))){
                        array_pop($types);
                    }
                    if(_empty_($types)){
                        $types = [];
                    }
                    if(_empty_($orderBy)){
                        $orderBy = 'created_at';
                    }
                    $master = $app_find_tab[0]['master'] ?? 0;
                }else{
                    if(!in_array($follow, [0, 1, 2])){
                        return $this->fail(200004);
                    }
                    $orderBy = _empty_default_($request->orderBy, 'created_at');
                    if(!in_array($orderBy, ['created_at', 'order', 'last_enter_at', 'follow_shop_at', 'buys'])){
                        return $this->fail(200004);
                    }
                    $order = _empty_default_($request->order, 'desc');
                    if(!in_array($order, ['desc', 'asc'])){
                        return $this->fail(200004);
                    }
                    $ids = _empty_default_($request->ids, '');
                    $master = _empty_default_($request->master, 0);

                    $types = _empty_default_($request->types, '');
                    if(is_string($types)){
                        $types = explode(',', $types);
                    }
                    if(_empty_(end($types))){
                        array_pop($types);
                    }
                    if(_empty_($types)){
                        $types = [];
                    }

                }
                if(is_string($ids)){
                    $ids = explode(',', $ids);
                }
                if(is_string($types)){
                    $types = explode(',', $types);
                }
                if($master == 1){
                    $master = 1;
                }else{
                    $master = 0;
                }
                $data = ShopUtils::goods_filter($is_tenant, $follow, $ids, $types, $orderBy, $order, $master);
            }
        }
        return $this->success($data);
    }

    /** 微信小程序预拉取
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function backgroundFetchPre(Request $request){
        $timestamp = $request->timestamp;
        if(time() - $timestamp > 60 ){
            return $this->fail(200009);
        }
        $path = $request->path;
        if($path){
            $path = str_replace('\\/', '/', $path);
        }
        $query = $request->query;
        $wx_scene = $request->scene;
        $uid = $request->uid;
        // ["1685360117","pages/tabbar/index/index",{},"1001",11691]
        if($path == 'pages/tabbar/index/index'){
            // 首页预拉取
            $data = PostsRepositores::list($uid, 10);
            _logger_(__file__, __line__, '预拉取......');
            return $this->success($data, 2009001);
        }
        return $this->success(['path'=>$path, 'query'=>$query]);
    }

    /** 微信小程序  周期性拉取
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     */
    public function backgroundFetchPeriod(Request $request){
        $timestamp = $request->timestamp;
        $uid = $request->uid;
        // 周期性拉取什么数据？ 1、用户信息， 2、
        if($uid > 0){

            $login_user = WxUser::where('id', $uid)->first(FieldUtils::userInfoColums());
            if($login_user){
                // 超级管理员
                if($login_user->is_official){
                    if(UserUtils::is_mini_supder_admin($login_user->id)){
                        $login_user->is_official = 2;
                    }
                }
                UserUtils::user_expend($login_user, true, true, true, true, 5);

                $time = time();
                $login_user->timeStamp = $time;

                return $this->success([
                    'user' => $login_user
                ]);
            }else{
                return $this->success(['test'=>'test']);
            }
        }else{
            return $this->success(['test'=>'test']);
        }

    }
    /**
     * 创建圈子
     * @param CircleRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function createCircle(CircleRequest $request)
    {
        // 验证
        $request->validate('addMsg');
        $uid = $request->uid;
        _limit_user('add:circle', $uid, 10);

        if(!UserUtils::is_user_can_speak($uid)){
            return $this->fail(200043, [
                'title' => '禁言中，无法言论',
                'content' => '是否前往解除限制',
                'confirmText' => '去解除',
                'target_type' => 6,
                'target_id' => '/pagesA/mine/unlock/unlock?user_id='.$uid
            ], '您当前处于禁言期间，无法言论');
        }

        $the_circle_id = _empty_default_($request->id, 0);
        $the_circle = null;
        if($the_circle_id > 0){
            // 修改圈子
            $the_circle = WxCircle::find($the_circle);
            if(_empty_($the_circle)){
                return $this->fail(200004);
            }
            $circle_user_id = $the_circle->user_id;
            if($circle_user_id != $uid && is_object_user_special($uid, $the_circle->tenant_id, true)){
                return $this->fail(200000, [], '您不是该圈的'.env('circle_user_call', '圈主'));
            }
        }else{
            $arr = UserUtils::user_action_permissions_check($uid,'create_circle');
            if($arr['code'] == 0){
                return $this->fail(200000, [], $arr['msg']);
            }
        }

        $circle_name = $request->circle_name;
        $circle_introduce = $request->circle_introduce;
        if($the_circle_id > 0){
            if($the_circle){
                if($the_circle->tenant_show == -1){
                    $exists = WxCircle::where('circle_name', $circle_name)->where('id', '<>', $the_circle_id)->exists();
                    if($exists){
                        return $this->fail(200010, [], '请联系管理员，你的圈子属于全站圈子，但存在其他圈子名称重复问题');
                    }
                }else{
                    $exists = WxCircle::where('circle_name', $circle_name)->where('id', '<>', $the_circle_id)->where('tenant_show', -1)->exists();
                    if($exists){
                        return $this->fail(200010, [], '已经存在这个名称的全站'.env('circle_call', '圈子'));
                    }
                    $exists = WxCircle::where('circle_name', $circle_name)->where('id', '<>', $the_circle_id)->where('tenant_show', $the_circle->tenant_show)->exists();
                    if($exists){
                        return $this->fail(200010, [], '这个名称的'.env('circle_call', '圈子').'已经存在啦，您换一个吧');
                    }
                }
            }
        }else{
            $exists = WxCircle::where('circle_name', $circle_name)->where('circle_state', 1)->exists();
            if($exists){
                return $this->fail(200010, [], '这个名称的'.env('circle_call', '圈子').'已经存在啦，您换一个吧');
            }
        }

        // 百度审核
        $need_manual_review = true;
        if(_empty_($circle_name) || _empty_($circle_introduce)){
            return $this->fail(200001);
        }

        $audit_create_cirlce = Settings::get('is_audit_create_cirlce', 0);
        if ($audit_create_cirlce == 0) {
            // 手动审核
            $need_manual_review = true;
        }else if($audit_create_cirlce == 2){
            // 机审
            $filter_result = BaiduUtils::text_filter($circle_name .'  '. $circle_introduce);
            if($filter_result){
                if($filter_result['hit_level'] == 2){
                    // 不合规
                    return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                }else if($filter_result['hit_level'] == 0){
                    // 审核通过
                    $need_manual_review = false;
                }
            }
        }else{
            // 不审核
            $need_manual_review = false;
        }

        // (0审核中，1正常，2驳回)
        $circle_state = 1;
        if($need_manual_review && !UserUtils::is_mini_supder_admin($uid)){
            $circle_state = 0;
        }

        $circle_id = WxCircleRepositores::add($request->all(), $circle_state);
        if($circle_id){
            UserInputSafeCheckJob::dispatch($uid, $circle_name .'  '. $circle_introduce);
            Utils::image_state_change([$request->head_portrait, $request->background_maps], 1);
            update_user_visit($uid, 2, $circle_id);
            if($circle_state === 0){
                UserUtils::assistant_notice_review(107, $circle_id);
            }
            return $this->success();
        }else{
            return $this->fail(200002);
        }
    }

    /*
     * app版本更新
     */
    public function appUpdate(Request $request){
        if(_empty_($request->versionName) || _empty_($request->type) ){
            return $this->fail(200001);
        }

        if($request->type == 1101){
            // 安卓
            $version = Settings::get('admin_app_android_update', []);
        }else{
            $version = Settings::get('admin_app_ios_update', []);
        }
        if(_empty_($version)){
            return $this->fail(200003);
        }
        $version = end($version);
        if(_version_compare($version['version'], $request->versionName) == '>'){
            /* res的数据说明
		 * | 参数名称	     | 一定返回 	| 类型	    | 描述
		 * | -------------|--------- | --------- | ------------- |
		 * | versionCode	 | y	    | int	    | 版本号        |
		 * | versionName	 | y	    | String	| 版本名称      |
		 * | versionInfo	 | y	    | String	| 版本信息      |
		 * | forceUpdate	 | y	    | boolean	| 是否强制更新  |
		 * | downloadUrl	 | y	    | String	| 版本下载链接（IOS安装包更新请放跳转store应用商店链接,安卓apk和wgt文件放文件下载链接）  |
		 */
            return $this->success(
                [
                    'versionCode' => 1,
                    'versionName' => $version['version'],
                    'versionInfo' => $version['desc'],
                    'updateType' => $version['type'] ?: 'solicit',
                    'downloadUrl' => $version['url']
                ]
            );
        }
        return $this->fail(200007);
    }

    /**
     * 统计搜索结果数量
     */
    public function searcheCountJson(Request $request)
    {
        $keyword = $request->keyword;
        $is_tenant = _empty_default_($request->isTenant, false);
        if(_empty_($is_tenant)){
            $is_tenant = false;
        }else{
            $is_tenant = true;
        }
        $hits = [];
        if($keyword){
            $trigger_word = Settings::get('app_search_trigger_word', []);
            if($trigger_word){
                foreach ($trigger_word as $word){
                    if(_array_key($word, 'match', 1) == 1){
                        if($keyword == $word['text']){
                            $hits = $word;
                            break;
                        }
                    }else if(_array_key($word, 'match', 1) == 2){
                        // 包含匹配
                        if(str_contains($keyword, $word['text'])){
                            $hits = $word;
                            break;
                        }
                    }

                }
            }
        }

        $posts_count = SearchUtils::search_post_count($keyword, $is_tenant);
        $circle_count = SearchUtils::search_circle_count($keyword, $is_tenant);
        $user_count = SearchUtils::search_user_count($keyword, $is_tenant);
        return $this->success(['posts_count'=>$posts_count, 'circle_count'=>$circle_count, 'user_count'=>$user_count, 'hits' => $hits]);
    }
    /*
     * 引导图
     */
    public function guide(Request $request){

        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return $this->fail(700000);
        }

        $admin_app_guide = Settings::get('admin_app_guide', []);
        if(_empty_($admin_app_guide)){
            return $this->fail(200003);
        }
        if(count($admin_app_guide) != 3){
            return $this->fail(200008);
        }

        return $this->success(['page1'=>[
            'title' => _array_key($admin_app_guide[0], 'title', ''),
            'desc' => _array_key($admin_app_guide[0], 'desc', ''),
            'img' => _array_key($admin_app_guide[0], 'img', '')
        ], 'page2'=>[
            'title' => _array_key($admin_app_guide[1], 'title', ''),
            'desc' => _array_key($admin_app_guide[1], 'desc', ''),
            'img' => _array_key($admin_app_guide[1], 'img', '')
        ], 'page3'=>[
            'title' => _array_key($admin_app_guide[2], 'title', ''),
            'desc' => _array_key($admin_app_guide[2], 'desc', ''),
            'img' => _array_key($admin_app_guide[2], 'img', '')
        ]]);
    }

    /**
     * 热门搜索列表
     */
    public function hotSearch()
    {
        return $this->success(WxSearchRepositores::hot_search(16));
    }

    /**
     * 首页轮播搜索关键字列表
     */
    public function HomeCarousel()
    {
        return $this->success(explode('|', Settings::get('app_search_carousel', '')));
    }


    /**
     * 获取条款内容
     */
    public function getClauseDetail(Request $request)
    {
        $id = $request->id;
        $data = WxClause::where('id', $id)->first(['title','content']);
        if($data){
            return $this->success($data);
        }
        return $this->fail(200003);
    }

    public function getUrlLink(Request $request){
        $path = ltrim(trim(_empty_default_($request->path, '')), '/');
        $query = _empty_default_($request->query, '');

        $short_last_path = $path;
        if(!_empty_($query)){
            $short_last_path .= '?'.$path;
        }

        $url_link_path = '';
        if(!_empty_($path)){
            $url_link_path .= ('/'.$path);
        }

        $new_app = new WeApp();
        $wxlink = $new_app->getWxLink();
        try {
            $link = $wxlink->genWxShortlink($short_last_path, '', true);
            $url_link =  $wxlink->genWxUrllink($url_link_path, $query);
            return $this->success(['short_link'=>$link, 'url_link'=>$url_link]);
        }catch (\Exception $e){
            return $this->fail(200004, [], $e->getMessage());
        }
    }

    public function getIcon(Request $request){
        $id = _empty_default_($request->id, 0);
        if(_empty_($id)){
            return $this->fail(200001);
        }
        $icon = WxIcon::find($id);
        if($icon){
            if(!_empty_($icon->img)){
                if($icon->img_width === null){
                    UpdateIconImgWHJob::dispatch($icon->id);
                }
            }
            return $this->success($icon);
        }else{
            return $this->fail(200003);
        }
    }

    /**
     * 获取说明内容
     */
    public function getHelp(Request $request){
        $help_type = $request->type;
        if(!in_array($help_type, array_keys(FieldUtils::getQuestionTypes()))){
            return $this->fail(200003);
        }
        $result = [
            'title' => FieldUtils::getQuestionTypes()[$help_type],
            'questions' => []
        ];
        $questions = WxQuestion::where('type', $help_type)->orderBy('updated_at', 'desc')->limit(200)->get();
        if(_empty_($questions)){
            return $this->success($result);
        }
        $result['questions'] = $questions;
        return $this->success($result);
    }



    private function default_configData(){
        global $__MINI_GLOBAL_PAYCODE_0__,$__MINI_GLOBAL_PAYCODE_1__,$__MINI_GLOBAL_PAYCODE_2__,$__MINI_GLOBAL_PAYCODE_3__,$__MINI_GLOBAL_PAYCODE_4__,$__MINI_GLOBAL_PAYCODE_5__,$__MINI_GLOBAL_PAYCODE_6__,$__MINI_GLOBAL_PAYCODE_7__;
        global $__MINI_GLOBAL_PAYCODE_8__,$__MINI_GLOBAL_PAYCODE_9__,$__MINI_GLOBAL_PAYCODE_10__,$__MINI_GLOBAL_PAYCODE_11__,$__MINI_GLOBAL_PAYCODE_12__,$__MINI_GLOBAL_PAYCODE_13__,$__MINI_GLOBAL_PAYCODE_14__;
        global $__MINI_GLOBAL_PAYCODE_15__,$__MINI_GLOBAL_PAYCODE_16__,$__MINI_GLOBAL_PAYCODE_17__,$__MINI_GLOBAL_PAYCODE_18__,$__MINI_GLOBAL_PAYCODE_19__,$__MINI_GLOBAL_PAYCODE_20__,$__MINI_GLOBAL_PAYCODE_21__,$__MINI_GLOBAL_PAYCODE_22__;
        global $__MINI_GLOBAL_PAYCODE_23__,$__MINI_GLOBAL_PAYCODE_24__,$__MINI_GLOBAL_PAYCODE_36__;
        global $__MINI_GLOBAL_DEVICE__,$__MINI_GLOBAL_TENANT_ID__,$__MINI_GLOBAL_CURRENT_USER_ID__,$__MINI_GLOBAL_IS_ADMIN_SUPER__,$__MINI_GLOBAL_CURRENT_PLAYER_ID__;

        $app_share_format = json_decode(Cache::get('app_share_format', ''), true) ?? [];
        if(_empty_($app_share_format)){
            CheckBatchCahceDataLossJob::dispatch();
        }

        if($__MINI_GLOBAL_TENANT_ID__ > 0){
            if(is_array($app_share_format)){
                $multi_text_share = Settings::get('app_multi_index_text_share', '', true);
                if($multi_text_share){
                    $app_share_format['app_share_right'] = $multi_text_share;
                }
            }
        }

        // 马甲账号
        $admin_played_users = json_decode(Cache::get(_multi_key('admin_played_users'), '')) ?? [];
        if($__MINI_GLOBAL_TENANT_ID__ > 0){
            // 分站模式下
            if($__MINI_GLOBAL_IS_ADMIN_SUPER__ || $__MINI_GLOBAL_CURRENT_PLAYER_ID__ > 0){
                $admin_played_users_primary = json_decode(Cache::get('admin_played_users', '')) ?? [];
                if($admin_played_users_primary){
                    $admin_played_users = array_merge($admin_played_users_primary, $admin_played_users);
                }
            }
        }

        if(_empty_($admin_played_users)){
//            CheckBatchCahceDataLossJob::dispatch();
        }

        $played_users = explode(',', Settings::get('app_admin_played_users', '', true));
        $played_users_ = [];
        if($played_users){
            foreach ($played_users as $play_user){
                if($play_user > 0){
                    $played_users_[] = (int)$play_user;
                }
            }
        }
        if($__MINI_GLOBAL_TENANT_ID__ > 0){
            // 分站模式下
            if($__MINI_GLOBAL_IS_ADMIN_SUPER__ || $__MINI_GLOBAL_CURRENT_PLAYER_ID__ > 0){
                $played_users_main = explode(',', Settings::get('app_admin_played_users', ''));
                if($played_users_main){
                    foreach ($played_users_main as $play_user){
                        if($play_user > 0){
                            $played_users_[] = (int)$play_user;
                        }
                    }
                }
            }
        }
        if($played_users_){
            $played_users_ = array_unique($played_users_);
        }

        $app_page_animation = json_decode(Cache::get('app_page_animation', '[]'), true);
        if(_empty_($app_page_animation)){
            CheckBatchCahceDataLossJob::dispatch();
        }

        $config_app_post_list_footer = json_decode( Cache::get(_multi_key('config:app:post:list:footer'), '{ "left": [1], "right": [2,3,4] }') );
        if(_empty_($config_app_post_list_footer)){
            CheckBatchCahceDataLossJob::dispatch();
        }

        $img_all_style_names = json_decode(Cache::get('img_all_style_names', '[]'), true);

        $default_share = Settings::get('img_share_default');
        if($__MINI_GLOBAL_TENANT_ID__ > 0){
            $multi_img_share = Settings::get('app_multi_index_img_share', '', true);
            if($multi_img_share){
                $default_share = $multi_img_share;
            }
        }

        return [
            'OK' => true,
            'version' => Settings::get('__global_config_version__', 1),
            'tab' => Settings::get('app_index_tab', [], true),
            'app' => [
                'multi' => Settings::get('is_multi_site', 0),
                'tenants' => Utils::get_online_tenants(),
                'mode' => is_mini_examine_mode() ? 'examine' : 'normal',
                'basic' => [
                    'intro_page' => Settings::get('admin_app_introduce_page'),
                    'url_schemes' => Settings::get('admin_app_url_schemes')
                ],
                'wechat' => [
                    'app' => [
                        'appid' => Settings::get('app_app_id'),
                    ],
                    'mini' => [
                        'appid' => Settings::get('app_id'),
                        'meta_appid' => Settings::get('app_meta_appid'),
                    ],
                    'mp' => [
                        'appid' => Settings::get('mp_app_id'),
                    ],
                    'web' => [
                        'appid' => '',
                    ],
                    'mch' => [
                        'appid' => Settings::get('mch_id'),
                    ]
                ],
                'phone' => [
                    'hard' => Settings::get('app_force_phone_hard', 0),
                    'pages' => Settings::get('app_force_phone_pages', []),
                ],
                'vip' => [
                    'options' => Settings::get('app_vip_options', []),
                    'clause' => Settings::get('app_vip_clause', 0),
                    'discount' => Settings::get('app_vip_paycontent_discount', 0),
                    'anonymous' => Settings::get('app_vip_anonymous_only', 0),
                ],
                "coins" => [
                    "name" => Settings::get('app_coin_name', '硬币'),
                    "rate" => Settings::get('app_coin_pay_rate', 100),
                    "percent_every" => _between_(Settings::get('app_coin_pay_percent_every', 100),0, 100),
                    "pay" => ($__MINI_GLOBAL_PAYCODE_17__ && Settings::get('app_coin_pay_open', 0) == 1),
                    "reward" => [
                        "mp" => [
                            "reward_unit" => Settings::get('ad_mp_reward_unit', ''),
                            "every" => Settings::get('ad_mp_reward_every', 20),
                            "times" => Settings::get('ad_mp_reward_every_day_times', 10)
                        ],
                        "uni" => [
                            "reward_unit" => Settings::get('ad_uni_reward_unit', ''),
                            "every" => Settings::get('ad_uni_reward_every', 20),
                            "times" => Settings::get('ad_uni_reward_every_day_times', 10)
                        ]
                    ],
                    "give_coin_open" => Settings::get('app_coin_give_switch', 1) == 1,
                    "give_options" => Settings::get('app_coin_give_options', []),
                    "give_clause" => Settings::get('app_coin_give_clause', 0),
                ],
                "lv" =>[
                    "permission" => [
                        'watch_video' => Settings::get('app_user_lv_watch_video', 1),
                        'publish_video' => Settings::get('app_user_lv_publish_video', 1),
                        'open_chat' => Settings::get('app_user_lv_open_chat', 1)
                    ]
                ],
                'ip' => [
                    'comment' => Settings::get('app_ip_comment_show', 0),
                    'post' => Settings::get('app_ip_post_show', 0),
                    'user' => Settings::get('app_ip_user_show', 0),
                ],
                'post' => [
                    'list' => [
                        'media' => Settings::get('sticky_list_media_style', 2, true),
                        'footer' =>  $config_app_post_list_footer,
                    ]
                ],
            ],
            'h5' => [
                'home' => Settings::get('app_h5_home'),
                'app_url' => Settings::get('admin_app_introduce_page', 'https://www.minisns.cn'),
                'redirect' => $__MINI_GLOBAL_PAYCODE_0__ ? (Settings::get('h5_normal_browser_redirect', 1) == 1 ? 1 : 0) : 0,
                'redirect_pages' => Settings::get('h5_normal_browser_redirect_pages', 5)
            ],
            'about'=> [
                'logo' => Settings::get('about_logo'),
                'name' => Settings::get('app_title'),
                'desc' => Settings::get('app_intro'),
                'slogan' => Settings::get('about_title'),
                'copyright' => Settings::get('about_copyright'),
                'icp' => Settings::get('about_icp'),
                'email' => Settings::get('about_sms'),
                'address' => Settings::get('about_address'),
                'phone' => Settings::get('about_phone'),
                'qq' => Settings::get('about_qq')
            ],
            'pay' => [
                'wechat' => Settings::get('app_app_pay_type_wechat'),
                'alipay' => Settings::get('app_app_pay_type_ali'),
                'apple' => Settings::get('app_app_pay_type_apple'),
                'mini2mp' => Settings::get('mini_ios_virtual_products_mp_pay', 0) == 1 ? 1 : 0
            ],
            'share' => [
                'format' => $app_share_format,
            ],
            'code' => [
                'mini' => Settings::get('app_mini_code'),
                'mp' => Settings::get('app_mp_code'),
                'app' => Settings::get('app_app_code'),
                'douyin' => Settings::get('app_douyin_code')
            ],
            'user' => [
                'login_style' => Utils::get_login_styles(),
                'register_style' => Utils::get_login_styles(0),
                'login_force' => Settings::get('app_login_force', 0),
                'default_user_name' => Settings::get('default_user_name_', ''),
                'user_background_maps' =>  Settings::get('user_background_maps'),
                'official_popup' => Settings::get('official_popup_poster'),
                'members_popup' => Settings::get('members_popup_poster'),
                'authentication_popup' => Settings::get('authentication_popup_poster'),
                'user_default_introduce' => Settings::get('app_user_introduce', '',true),
            ],
            'img' => [
                'empty' => Settings::get('img_empty'),
                'default' => Utils::imgWithStyle(Settings::get('img_default'), 1),
                'default_share' => $default_share,
                'post_poster' => Settings::get('img_post_poster_default'),
                'default_avatar' => Settings::get('img_default_avatar'),
                'topic_avatar' => Settings::get('img_default_topic_avatar'),
                'favicon_ico' => Settings::get('browser_favicon_ico'),
                'styleNames' => $img_all_style_names,
                'phone_popup' => Settings::get('img_get_phone_popup', 'https://img.mini.minisns.cn/images/phone.jpg'),
                "reward_select" => Settings::get('popup_reward_select_img', 'https://img.mini.minisns.cn/icons/rain.png'),
                "beliked_count" => Settings::get('popup_beliked_count_img', 'https://img.mini.minisns.cn/icons/collect-likes.png'),
            ],
            'audit' => [
                'is_audit_posts' => Settings::get('is_audit_posts', 0) == '1' ? 1 : 0,
                'is_audit_comment' => Settings::get('is_audit_comment', 0) == '1' ? 1 : 0,
                'is_audit_user_info' => Settings::get('is_audit_user_info', 0) == '1' ? 1 : 0,
                'is_user_center_show_posts' => 0,
                'is_audit_create_cirlce' => Settings::get('is_audit_create_cirlce', 0) == '1' ? 1 : 0,
                'is_reward' => Settings::get('is_reward', '1') == '1' ? 1 : 0,
                'is_withdrawal' => Settings::get('is_withdrawal') == '1' ? 1 : 0,
            ],
            'color' => [
                '--color-primary' => Settings::get('uni_color_primary', '#fc3a72')
            ],
            'page' => [
                'animation' => $__MINI_GLOBAL_PAYCODE_19__ ? $app_page_animation : [],
                'index' => [
                    'header' => AdminUtils::get_nav_left_right_icon(  ($__MINI_GLOBAL_DEVICE__ == 'mp' ? 'app_index_header_icon' : 'app_app_index_header_icon')),
                    'channels' => [
                        'style' => Settings::get('app_index_top_nav_style', 0)
                    ],
                    'searchCarousel' => explode('|', Settings::get('app_search_carousel', '', true)),
                    'banner' => WxSlideshow::wherein('id', explode(',', Settings::get('app_index_banner', '', true)))->orderBy(DB::raw('FIND_IN_SET(id, "' . Settings::get('app_index_banner', '', true) . '"' . ")"))->get(['id','title', 'poster', 'target_id', 'slideshow_type']),
                    'banner_height' => Settings::get('app_index_banner_height', 300, true),
                    'notice' => Settings::get('app_index_notice', [], true),
                    'nav' => Settings::get('app_index_nav', [], true),
                    'shop_nav' => Settings::get('app_index_shop_nav', [], true),
                    'flow' => Settings::get('app_index_flow', 1, true)
                ],
                'find' => [
                    'header' => AdminUtils::get_nav_left_right_icon('app_find_header_icon', true),
                    'banner' => WxSlideshow::wherein('id', explode(',', Settings::get('app_find_banner', '', true)))->orderBy(DB::raw('FIND_IN_SET(id, "' . Settings::get('app_find_banner', '', true) . '"' . ")"))->get(['id','title', 'poster', 'target_id', 'slideshow_type']),
                    'tabs' => Settings::get('app_find_tab', [], true)
                ],
                'find2' => [
                    'header' => AdminUtils::get_nav_left_right_icon('app_find2_header_icon', true),
                    'banner' => WxSlideshow::wherein('id', explode(',', Settings::get('app_find2_banner', '', true)))->orderBy(DB::raw('FIND_IN_SET(id, "' . Settings::get('app_find2_banner', '', true) . '"' . ")"))->get(['id','title', 'poster', 'target_id', 'slideshow_type']),
                    'tabs' => Settings::get('app_find2_tab', [], true)
                ],
                'shop' => [
                    'accordion' => Settings::get('is_app_shop_accordion', true) == '1' ? 1 : 0,
                    'hot' => Settings::get('is_app_shop_hot_list', true) == '1' ? 1 : 0,

                    'servicer' => [
                        'servicer_target_type' => Settings::get('app_shop_servicer_target_type'),
                        'servicer_target_id' => Settings::get('app_shop_servicer_target_id'),
                    ]
                ],
                'notice' => [
                    'mp_follow' => Settings::get('app_notice_mp_follow', 1),
                    'style' => Settings::get('app_notice_img_style', 0),
                    'icons' => [
                        'system' => Settings::get('app_notice_img_system', ''),
                        'like' => Settings::get('app_notice_img_like', ''),
                        'comment' => Settings::get('app_notice_img_comment', ''),
                        'servicer' => Settings::get('app_notice_img_servicer', ''),

                        'mp_servicer' => Settings::get('app_notice_img_servicer_mp_servicer', 0, true),
                        'servicer_target_type' => Settings::get('app_notice_img_servicer_target_type', 1, true),
                        'servicer_target_id' => Settings::get('app_notice_img_servicer_target_id', null, true),

                        'circle' => Settings::get('app_notice_img_circle', ''),
                    ],
                ],
                'mine' => [
                    'header' => AdminUtils::get_nav_left_right_icon('app_mine_header_icon'),
                    'style' => Settings::get('app_user_list_style', 0),
                ],
                'circle' => [
                    'style' => Settings::get('app_circle_list_style', 0, true),
                ],
                'topic' => [
                    'style' => Settings::get('app_topic_list_style', 0),
                ],
                'circle_class' => [
                ],
                'qa' => [
                    'type' => Settings::get('app_qa_types', [])
                ],
                'create' => [
                    "fix2_left" => Settings::get('app_publish_tools_fixed2_left', ['location', 'circle']),
                    "fix2_right" => Settings::get('app_publish_tools_fixed2_right', ['pay']),
                    'imagetext_switch' => Settings::get('app_publish_imagetext_switch', 1, true) == 1,
                    'max_file' => Settings::get('app_upload_max_files', 5, true),
                    'max_sounds' => Settings::get('app_upload_max_sounds', 1, true),
                    'max_vote_option' => Settings::get('app_vote_max_options', 10, true),
                    'max_coins' => Settings::get('app_pay_max_coins', 10000),
                    'max_blance' => (!$__MINI_GLOBAL_PAYCODE_7__ ? 0 : Settings::get('app_pay_max_balance', 1000)),
                    'video_press' => Settings::get('app_upload_video_compress', 1, true),
                    'circle_require' => Settings::get('app_publish_circle_required', 0, true),
                    'media_require' => Settings::get('app_publish_media_required', 0, true),
                    'edit_need' => Settings::get('app_publish_edit_need_coin', ($__MINI_GLOBAL_TENANT_ID__ > 0 ? Settings::get('app_publish_edit_need_coin', 100) : 100),  true)
                ],
                'login' => [
                    'bg' => Settings::get('app_login_bg', 'https://img.mini.minisns.cn/2023/03/25/68b11834f85f49711ae1ba875f7d7ab1.jpg', true),
                    'scroll' => Settings::get('app_login_bg_scroll', 1, true),
                ],
                'sticky' => [
                    'video_slide' => Settings::device_get('sticky_video_slide_in_mp', 'sticky_video_slide_in_h5', 'sticky_video_slide_in_android_app', 'sticky_video_slide_in_ios_app', '', false, true) == 1,
                ]
            ],
            'admin' => [
                'played' => $admin_played_users,
                'playlist' => $played_users_,
                'nav' => Settings::get('app_admin_nav', [])
            ],
            'events' => $this->get_page_events(),
            'pays' => [
                'paycode_0' => $__MINI_GLOBAL_PAYCODE_0__,
                'paycode_1' => $__MINI_GLOBAL_PAYCODE_1__,
                'paycode_2' => $__MINI_GLOBAL_PAYCODE_2__,
                'paycode_3' => $__MINI_GLOBAL_PAYCODE_3__,
                'paycode_4' => $__MINI_GLOBAL_PAYCODE_4__,
                'paycode_5' => $__MINI_GLOBAL_PAYCODE_5__,
                'paycode_6' => $__MINI_GLOBAL_PAYCODE_6__,
                'paycode_7' => $__MINI_GLOBAL_PAYCODE_7__,
                'paycode_8' => $__MINI_GLOBAL_PAYCODE_8__,
                'paycode_9' => $__MINI_GLOBAL_PAYCODE_9__,
                'paycode_10' => $__MINI_GLOBAL_PAYCODE_10__,
                'paycode_11' => $__MINI_GLOBAL_PAYCODE_11__,
                'paycode_12' => $__MINI_GLOBAL_PAYCODE_12__,
                'paycode_13' => $__MINI_GLOBAL_PAYCODE_13__,
                'paycode_14' => $__MINI_GLOBAL_PAYCODE_14__,
                'paycode_15' => $__MINI_GLOBAL_PAYCODE_15__,
                'paycode_16' => $__MINI_GLOBAL_PAYCODE_16__,
                'paycode_17' => $__MINI_GLOBAL_PAYCODE_17__,
                'paycode_18' => $__MINI_GLOBAL_PAYCODE_18__,
                'paycode_19' => $__MINI_GLOBAL_PAYCODE_19__,
                'paycode_20' => $__MINI_GLOBAL_PAYCODE_20__,
                'paycode_21' => $__MINI_GLOBAL_PAYCODE_21__,
                'paycode_22' => $__MINI_GLOBAL_PAYCODE_22__,
                'paycode_23' => $__MINI_GLOBAL_PAYCODE_23__,
                'paycode_24' => $__MINI_GLOBAL_PAYCODE_24__,
                'paycode_36' => $__MINI_GLOBAL_PAYCODE_36__,
            ],
            'pupop' => get_site_meta(_multi_key('app_publish_popup_config'), 'j')
        ];
    }

    private function get_page_events(){
        $page_events = [];
        WxPageEvent::all()->map(function ($v) use (&$page_events){
            if(isset($page_events[$v->scene])){
                $page_events[$v->scene][] = $v;
            }else{
                $page_events[$v->scene] = [$v];
            }
        });
        return $page_events;
    }

    private function third_configData(){
        return [
            'OK' => true,
            'version' => Settings::get('__global_config_version__', 1),
        ];
    }

    private function fourth_configData(){
        return [
            'OK' => true,
            'version' => Settings::get('__global_config_version__', 1),
            'pets' => [

            ]
        ];
    }

    private function second_configData(){
        global $__MINI_GLOBAL_PAYCODE_0__, $__MINI_GLOBAL_PAYCODE_30__;
        $mine_list = Settings::get('app_user_about_mine_list', []);
        if($__MINI_GLOBAL_PAYCODE_0__){
            if(Settings::get('app_user_about_mine_minisns_show', 1) == 1){
                $mine_list[] = [
                    'name' => '迷你SNS驱动',
                    'type' =>11,
                    'target' => 'wx3663aa159a362f52|gh_31aec555bf2f|pages/tabbar/index/index?from_user=' . Settings::get('app_user_about_mine_minisns_id', 11691)
                ];
            }
        }else{
            $mine_list[] = [
                'name' => '迷你SNS驱动',
                'type' =>11,
                'target' => 'wx3663aa159a362f52|gh_31aec555bf2f|pages/tabbar/index/index?from_user=' . Settings::get('app_user_about_mine_minisns_id', 11691)
            ];
        }

        // 首页是否瀑布流
        $index_is_waterfall = false;
        $index_tab = json_decode(Settings::get('app_index_tab', '', true), true);
        if(!_empty_($index_tab)){
            $index_is_waterfall = _array_key($index_tab[1], 'waterfall', '0') == '1';
        }

        $publish2_square_list = explode(',', Settings::get('app_publish2_square_list', '', true));
        $publish2_square_icons = [];
        if($publish2_square_list){
            $publish2_square_icons = WxIcon::whereIn('id', $publish2_square_list)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $publish2_square_list) . '"' . ")"))->limit(2)->get();
        }

        $app_publish2_post_show = explode(',', Settings::get('app_publish2_post_show', '', true));
        $publish2_post_show = [];
        if($app_publish2_post_show && $app_publish2_post_show[0]){

            $publish2_post_show = [
                'id' => $app_publish2_post_show[0],
                'title' => PostUtils::get_the_title('', $app_publish2_post_show[0]),
                'user' => UserUtils::get_simple_cached_user(WxPost::where('id', $app_publish2_post_show[0])->value('user_id'), ['id', 'user_name', 'user_avatar'])
            ];
        }

        $cosConfig = Settings::get('cosv5', []);

        return [
            'OK' => true,
            'version' => Settings::get('__global_config_version__', 1),
            'page' => [
                'sticky' => [
                    'statement' => Settings::get('sticky_content_statement', '', true),
                    'slider_comment_page' => Settings::get('sticky_reach_bottom_comment_page', 0),
                    'is_recommendation' => Settings::get('is_sticky_content_recommendation', 0, true),
                ],
                'circle' => [
                    'publish_icon' => Settings::get('app_circle_list_publish_icon', 0, true),
                ],
                'wallpapers' => [
                    'name' => Settings::get('app_wallpapers_name', '图集')
                ],
                'mine' => [
                    'about' => [
                        'list' => $mine_list
                    ],
                    'earnings' => [
                        'recharge_list' => Settings::get('app_balance_recharge_list', []),
                        'balance_clause' => Settings::get('app_balance_recharge_clause', 0),
                        'child_refund_clause' => Settings::get('app_balance_recharge_child_refund_clause', 0),
                        'withdrawal_way' => Settings::get('app_balance_withdrawal_way', []),
                        'withdrawal_min_once' => Settings::get('app_balance_withdrawal_min_once', 1),
                        'withdrawal_max_once' => Settings::get('app_balance_withdrawal_max_once', 200),
                        'withdrawal_day_times' => Settings::get('app_balance_withdrawal_day_times', 3),
                        'withdrawal_tips' => Settings::get('app_balance_withdrawal_tips', [])
                    ]
                ],
                'publish2' => [
                    'bg' => Settings::get('app_publish2_bg_img', 'https://img.mini.minisns.cn/images/hbx/publish2-bg.jpg'),
                    'post' => $publish2_post_show,
                    'items' => $publish2_square_icons
                ],
                'used' => [
                    'index' => [
                        'header' => AdminUtils::get_nav_left_right_icon('app_used_header_icon'),
                        'banner' => $__MINI_GLOBAL_PAYCODE_30__ ? WxSlideshow::wherein('id', explode(',', Settings::get('used_mall_index_banner', '', true)))->orderBy(DB::raw('FIND_IN_SET(id, "' . Settings::get('used_mall_index_banner', '', true) . '"' . ")"))->get(['id','title', 'poster', 'target_id', 'slideshow_type']) : [],
                    ],
                    'detail' => [
                        'map' => Settings::get('used_mall_detail_self_pick_show_map', 1, true),
                        'buy' => Settings::get('used_mall_detail_can_buy', 1)
                    ],
                    'push' => [
                        'force_classify' => Settings::get('used_mall_push_force_classify', 0, true) == 1 ? 1 : 0
                    ]
                ],
                'bureau' => [
                    'index' => [
                        'header' => AdminUtils::get_nav_left_right_icon('app_bureau_header_icon'),
                        'banner' => WxSlideshow::wherein('id', explode(',', Settings::get('app_bureau_index_banner', '', true)))->orderBy(DB::raw('FIND_IN_SET(id, "' . Settings::get('app_bureau_index_banner', '', true) . '"' . ")"))->get(['id', 'poster', 'target_id', 'slideshow_type']),
                    ],
                    'settle_in' => [
                        'bg' => Settings::get('app_bureau_club_settle_in_bg', '')
                    ],
                    "detail" => [
                        "price" => Settings::get('app_bureau_club_price_bg', 'https://img.mini.minisns.cn/2024/06/26/0/aadf56680a534ae75986f738aa35d40d.png'),
                        "price_gray" => Settings::get('app_bureau_club_price_gray_bg', 'https://img.mini.minisns.cn/2024/06/26/0/60fad64bb24e9effc4e7a08195f5b5a4.png')
                    ]
                ],
                'reward' => [
                    'inspire' => [
                        'img' => Settings::get('ad_reward_inspire_img', 'https://img.mini.minisns.cn/images/inspire-face.png')
                    ]
                ],
                'certification' => [
                    'img_tip' => Settings::get('app_user_authenticate_img_tip', [])
                ],
                'find' => [
                    'icons' => [
                        'header' => AdminUtils::get_nav_left_right_icon('app_find2_header_icon', true),
                        'icons' => Settings::get('app_find9_icons', [], true)
                    ],
                ],
                'voter' => [
                    'header' => AdminUtils::get_nav_left_right_icon('app_voter_header_icon', true),
                    'banner' => WxSlideshow::wherein('id', explode(',', Settings::get('app_voter_banner', '', true)))->orderBy(DB::raw('FIND_IN_SET(id, "' . Settings::get('app_voter_banner', '', true) . '"' . ")"))->get(['id','title', 'poster', 'target_id', 'slideshow_type']),
                    'tabs' => Settings::get('app_voter_tab', [], true)
                ],
            ],
            'emoji' => [
                'page_1' =>  json_decode(Settings::get('app_emoji_page_1', ''), true),
                'page_2' => json_decode(Settings::get('app_emoji_page_2', ''), true),
                'page_3' => json_decode(Settings::get('app_emoji_page_3', ''), true),
            ],
            'invite' => [
                'status' => Settings::get('user_invite_benefit_status', 0) == 1,
                'lv' => Settings::get('app_user_lv_invite_benefit', 2),
                'max_layer' => Settings::get('user_invite_benefit_max_layer', 3),
            ],
            'app' => [
                'withdrawal' => [
                    'platform_percent' => _between_(Settings::get('app_withdrawal_platform_percent', 10.0), 0, 100),
                    'type' => Settings::get('user_withdrawal_type', 0)
                ],
                'contact_apply' => [
                    'platform_percent' => _between_(Settings::get('app_contact_pay_platform_percent', 10.0), 0, 100),
                ]
            ],
            'placeholder' => [
                'publish_word' => Settings::get('app_publish_placeholder_text', '', true),
            ],
            'user' => [
                'labels' => Settings::get('app_user_labels', [],true)
            ],
            'waterfall' => [
                'scene_1' => $index_is_waterfall,
                'scene_6' => Settings::get('app_circle_list_style', '0') == '1',
                'scene_7' => Settings::get('app_topic_list_style', '0') == '1',
                'scene_8' => Settings::get('app_user_list_style', '0') == '1',
            ],
            'used' => [
                'share' => [
                    'index_title' => Settings::get('used_mall_index_share_title', ''),
                    'index_image' => Settings::get('used_mall_index_share_image', ''),
                    'detail_title' => Settings::get('used_mall_detail_share_title', '[good_title] - 限制'),
                ],
            ],
            'cos' => [
                'bucket' => _array_key($cosConfig, 'bucket', '') . '-' ._array_key($cosConfig, 'appId', ''),
                'region' => _array_key($cosConfig, 'region', '')
            ],
            'bureau' => [
                'tags' => Settings::get('app_bureau_tags_', []),
                'club' => [
                    'avatar' => Settings::get('app_bureau_club_default_avatar', ''),
                    'clause' => Settings::get('app_bureau_club_settle_in_clause', 0)
                ],
                'share' => [
                    'index_title' => Settings::get('app_bureau_index_share_title', ''),
                    'index_image' => Settings::get('app_bureau_index_share_image', ''),
                    'detail_title' => Settings::get('app_bureau_detail_share_title', '[bureau_title] - 组局活动'),
                ],
            ]
        ];
    }


    /*
     * 返回站点信息
     */
    public function configData(Request $request){
        global $__MINI_GLOBAL_FRONT_VERSION__;
        $device = $request->header('device','mp');
        if(_empty_($device)){
            $device = 'mp';
        }
        $uid = $request->uid;
        if(_empty_($uid)){
            $uid = 0;
        }
        $platform = $request->header('platform','android');
        if(!in_array($platform, ['android', 'ios'])){
            $platform = 'android';
        }

        global $__MINI_GLOBAL_TENANT_ID__;

        $which = $request->which;
        if($which && $which > 1 && $which <= 5){

        }else{
            $which = '';
        }
        if(_empty_($device) || !in_array($device, ['app', 'mp', 'h5', 'pc'])){
            return $this->fail(200001);
        }
        // app需要分安卓和ios
        if($device == 'app'){
            $device = $device.':'.$platform;
        }
        $device = 'tenant_'.$__MINI_GLOBAL_TENANT_ID__ . ':' . $device;

        $the_cache_key = 'configData'.$which.':'.$__MINI_GLOBAL_FRONT_VERSION__.':'.$device;

        $data = json_decode(Cache::tags('configData')->get($the_cache_key, '[]'), true);
        if(!_empty_($data)){

        }else{
            if($which == 3){
                $data = $this->third_configData();
            }else if($which == 4){
                $data = $this->fourth_configData();
            }else if($which == 2){
                $data = $this->second_configData();
            }else{
                $data = $this->default_configData();
            }
            if($which == 3){
                // 特殊用户自定义的配置
                Cache::tags('configData')->put($the_cache_key, json_encode($data), 3600 * 3 );
            }else{
                Cache::tags('configData')->put($the_cache_key, json_encode($data));
            }
        }
        if(!($which > 1)){
            if($data && is_array($data) && $data['app']['mode'] == 'examine' && $uid > 0){
                if(!is_mini_examine_mode(11)){
                    $data['app']['mode'] = 'normal';
                }
            }
        }
        return $this->success($data);
    }

    /**
     * 用户搜索列表
     */
    public function mySearch(Request $request)
    {
        $uid = $request->uid;
        if ($uid) {
            return $this->success(WxSearch::where('user_id', $uid)
                ->orderBy('id', 'desc')
                ->get(['search_content', 'id']));
        }else{
            return $this->success([]);
        }
    }

    public function realtime_post(Request $request){
        global $__MINI_GLOBAL_PAYCODE_12__;
        if($__MINI_GLOBAL_PAYCODE_12__){

            $type = $request->type;
            $posts = RealtimeUtils::get_top_posts();
            if($posts){
                if($type == '50'){
                    $posts['posts'] = array_slice($posts['posts'], 0, 50);
                }else{
                    $posts['posts'] = array_slice($posts['posts'], 0, 10);
                }
                $posts['format_time'] = format_datetime($posts['update_time']);
                return $this->success($posts);
            }
        }
        return $this->fail(200003);
    }

    public function realtime_topics(Request $request){
        global $__MINI_GLOBAL_PAYCODE_12__;
        if($__MINI_GLOBAL_PAYCODE_12__){
            $topics = RealtimeUtils::get_topic_top();
            if($topics){
                $topics['topics'] = array_slice($topics['topics'], 0, 10);
                if($topics['topics']){
                    for ($i = 0; $i < count($topics['topics']); $i++){
                        $topics['topics'][$i]['head_portrait'] = Utils::imgWithStyle($topics['topics'][$i]['head_portrait'], 2);
                    }
                }
                $topics['format_time'] = format_datetime($topics['update_time']);
                return $this->success($topics);
            }
        }else{
            $topics = [
                'topics' => [],
                'format_time' => ''
            ];
            $tags = WxTag::where('tags_state', 0)
                ->where('tags_number', '>', 0)
                ->orderBy('tags_number', 'desc')->limit(10)->get();
            $tags->map(function ($items) {
                $items->tags_number = WxPostsTag::where('tags_id', $items->id)->count();
                if(_empty_($items->head_portrait)){
                    $items->head_portrait = Settings::get('img_default_topic_avatar');
                    TopicImgJob::dispatch($items->id);
                }
            });
            if($tags){
                $topics['topics'] = $tags;
            }

            return  $this->success($topics);
        }
    }

    public function captcha_process(Request $request){
        $action = _empty_default_($request->action);
        if($action == 'src'){
            $code = WxCaptchaImg::where('status', 1)->inRandomOrder()->first();
            if(!$code){
                return $this->fail(200008, [], '管理员暂未配置人机验证码库');
            }

            $rotate = rand(10, 340);
            $random_str = Str::random(8);
            Cache::put('captcha:'.$random_str, $rotate, 60);
            return $this->success([
                'src' => ImageUtils::get_img_base64($code->img, $rotate),
                'random' => $random_str,
            ]);
        }else if($action == 'check'){
            global $__MINI_GLOBAL_DEVICE__,$__MINI_GLOBAL_PLATFORM__,$__MINI_GLOBAL_IP__;
            $random = _empty_default_($request->random, '');
            if(_empty_($random)){
                return $this->fail(200001);
            }
            $rotate = Cache::get('captcha:'.$random);
            if(_empty_($rotate)){
                return $this->fail(200044);
            }
            $margin = 25;
            $rotationAngle = _empty_default_($request->rotationAngle, 0);
            $totalRotation = ($rotationAngle + $rotate) % 360;
            if ($totalRotation <= $margin || $totalRotation >= (360 - $margin)) {
                Cache::put('captcha:ip:'.$__MINI_GLOBAL_DEVICE__.':'.$__MINI_GLOBAL_PLATFORM__.':'.$__MINI_GLOBAL_IP__, 1, 600);
                return $this->success();
            }else{
                return $this->fail(200004, [], '验证未通过');
            }
        }
        return $this->fail(200001);
    }

    public function university(Request $request){
        $keyword = _empty_default_($request->keyword, '');
        $scene = _empty_default_($request->scene, '');
        $sid = _empty_default_($request->sid, null);
        $user_id = _empty_default_($request->user_id, 0);
        if($scene == 'certify'){
            $query = WxUniversity::where('is_certify', 1);
        }else{
            $query = WxUniversity::whereNotNull('sid');
        }
        if($user_id > 0){
            $sid = WxUserStudentCertify::where('user_id', $user_id)->value('sid');
            if(_empty_($sid)){
                return $this->fail(200003, [], '查询不到该用户的学生认证信息');
            }
        }
        if($sid){
            $query = $query->where('sid', $sid);
        }

        if($keyword){
            $query = $query->where(function ($query) use ($keyword) {
                if(is_numeric($keyword)){
                    $query->orWhere('name', 'like', '%' . $keyword . '%')
                        ->orWhere('sid', $keyword);
                }else{
                    $query->orWhere('name', 'like', '%' . $keyword . '%')->orWhere('charge', 'like', '%' . $keyword . '%')->orWhere('location', 'like', '%' . $keyword . '%');
                }
            });
        }

        $data = $query->orderBy('order', 'asc')->simplePaginate(20);
        if($data){
            return $this->success($data);
        }
        return $this->fail(200003);
    }

    public function idd(){
        if(!file_exists(storage_path('app/idd/idd.json'))){
            return $this->fail(200003);
        }
        return $this->success(json_decode(file_get_contents(storage_path('app/idd/idd.json'))));
    }

    /**
     * 用户删除搜索记录
     * id
     */
    public function myDelSearch(Request $request)
    {
        $id = $request->id;
        return $this->success(WxSearch::where('id', $id)->delete());
    }
    /**
     * 用户删除全部搜索记录
     * id
     */
    public function myDelAllSearch(Request $request)
    {
        $uid = $request->uid;
        return $this->success(WxSearch::where('user_id', $uid)->delete());
    }

    public function towebview($action, $unique){
        $url = '';
        if($action == 'mplogin'){
            config(['services.wechat_service_account.redirect' => env('APP_URL').'/common/webview/action?action=mplogin&unique='.$unique]);
            return Socialite::driver('wechat_service_account')->redirect();
        }
        if($action == 'mpbind'){
            config(['services.wechat_service_account.redirect' => env('APP_URL').'/common/webview/action?action=mpbind&unique='.$unique]);
            return Socialite::driver('wechat_service_account')->redirect();
        }

        return view('common/webview', compact('url'));
    }

    public function webview(Request $request){
        $uid = $request->uid;
        $action = $request->action;
        $unique = $request->unique;
        $pre_scene = _empty_default_($request->pre_scene, 0);
        $pre_scene_id = _empty_default_($request->pre_scene_id, 0);
        $url = '';

        if(!_empty_($pre_scene)){
            Cache::put($action.':unique:'.$unique.':scene', json_encode([
                'scene' => $pre_scene,
                'pre_scene_id' => $pre_scene_id
            ]), 120);
        }

        if($action == 'mplogin'){
            config(['services.wechat_service_account.redirect' => env('APP_URL').'/common/webview/action?action=mplogin&unique='.$unique]);
            return Socialite::driver('wechat_service_account')->redirect();
        }
        if($action == 'mpbind'){
            config(['services.wechat_service_account.redirect' => env('APP_URL').'/common/webview/action?action=mpbind&unique='.$unique]);
            return Socialite::driver('wechat_service_account')->redirect();
        }

        return view('common/webview', compact('url'));
    }


    public function webviewAction(Request $request){
        $action = $request->action;
        $unique = $request->unique;
        if($action == 'mpuser'){
            $userData = Socialite::driver('wechat_service_account')->user();
            if($userData){
                $user = $userData->user;
                $data = [
                    'openId'=>$user['openid'], 'avatarUrl'=>$user['headimgurl'] ?: '', 'city'=>$user['city'] ?: '', 'country'=>$user['country'] ?: '',
                    'province'=>$user['province'] ?: '', 'language'=>'','nickName'=>$user['nickname'] ?: '',
                    'gender'=>$user['sex'] ?: 0, 'unionId'=>$user['unionid'] ?? ''
                ];
                $wxUserModel = new WxUser();
                $r = $wxUserModel->registerUser($data, 'mp');
                if($r > 0){
                    return '获取成功！';
                }else{
                    return '获取失败';
                }
            }
            return '未获取到用户信息';
        }
        if($action == 'mplogin'){
            $userData = Socialite::driver('wechat_service_account')->user();
            if($userData){
                $user = $userData->user;

                $data = [
                    'openId'=>$user['openid'], 'avatarUrl'=>$user['headimgurl'] ?: '', 'city'=>$user['city'] ?: '', 'country'=>$user['country'] ?: '',
                    'province'=>$user['province'] ?: '', 'language'=>'','nickName'=>$user['nickname'] ?: '',
                    'gender'=>$user['sex'] ?: 0, 'unionId'=>$user['unionid'] ?? ''
                ];
                $wxUserModel = new WxUser();
                $user_id = $wxUserModel->registerUser($data, 'mp');

                if($user_id > 0){
                    if($user_id && $unique){
                        Cache::put('mini:mplogin:unique:' . $unique, $user_id, 10 * 60);
                    }

                    $to_path = 'pages/tabbar/index/index?';
                    $scene = json_decode(Cache::get($action.':unique:'.$unique.':scene', '[]'), true);
                    if($scene && _array_key($scene, 'scene', 0) > 0)
                    if($scene['scene'] == 31){
                        $to_path = 'pagesA/mine/members/members?';
                    }else if($scene['scene'] == 84){
                        $to_path = 'pagesC/promotion/post?';
                    }
                    $href = Settings::get('app_h5_home') .'/#/'.$to_path.'action=mplogin&unique='. $unique;
                    $html = '
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>正在获取用户授权信息...请稍后</title>
</head>
<body>
<div>获取成功，若未自动跳转，可手动关闭即可</div>
<script>
function redict(){
    window.location.href = \''. $href .'\'
}
redict();
</script>
</body>
</html>
';
                    return $html;
                }else{
                    _logger_(__file__, __line__, '发生错误2...');
                }
            }else{
                _logger_(__file__, __line__, '发生错误...');
            }
        }
        if($action == 'mpbind'){
            $userData = Socialite::driver('wechat_service_account')->user();
            if($userData){
                $user = $userData->user;
                $data = [
                    'openId'=>$user['openid'], 'avatarUrl'=>$user['headimgurl'] ?: '', 'city'=>$user['city'] ?: '', 'country'=>$user['country'] ?: '',
                    'province'=>$user['province'] ?: '', 'language'=>'','nickName'=>$user['nickname'] ?: '',
                    'gender'=>$user['sex'] ?: 0, 'unionId'=>$user['unionid']
                ];
                $wxUserModel = new WxUser();
                $r = $wxUserModel->registerUser($data, 'mp');
                if($r > 0){
                    return '<html><head><title>获取成功！请截图关注公众号</title></head><body><h1 style="text-align: center">获取成功！截图关注公众号即可</h1><div style="text-align: center;justify-content: center;margin: auto"><img style="max-width: 300px;" src="'.Settings::get('app_mp_code').'"></div></body></html>';
                }else{
                    return '获取失败，可重新再试';
                }
            }
            return '未获取到用户信息';
        }

        return 'success';
    }

    public function getActivityList(Request $request){
        return $this->success(WxActivity::orderBy('created_at', 'desc')->get());
    }


}